package cn.cdeden.knowledge.controller.label;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.FilesLabelRecord;
import cn.cdeden.knowledge.domain.FilesLabelRecordDelete;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.vo.FilesLabelRecordVo;
import cn.cdeden.knowledge.enums.FileLabelTypeEnums;
import cn.cdeden.knowledge.enums.TeamParamEnum;
import cn.cdeden.knowledge.service.EnterprisePermService;

import cn.cdeden.knowledge.service.FilesLabelRecordService;
import cn.cdeden.knowledge.service.TeamMemberService;
import cn.cdeden.knowledge.service.TeamRelevanceRoleService;
import cn.cdeden.system.api.domain.enums.EnterprisePermTypeEnum;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.undertow.util.BadRequestException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;


import java.util.List;

/**
 * 标签: 记录管理
 * @author Yu.
 * @date 2022-10-25
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
//@Api(tags = "标签: 记录管理")
@RequestMapping("/api/filesLabelRecord")
public class FilesLabelRecordController {

    private final FilesLabelRecordService filesLabelRecordService;

    private final EnterprisePermService enterprisePermService;
//
    private final TeamRelevanceRoleService teamRelevanceRoleService;

    private final TeamMemberService teamMemberService;



    @GetMapping("/query")
////    @Log("标签:查询用户标签记录")
////    @ApiOperation("标签:查询用户标签记录")
    public R<TableDataInfo<FilesTree>> query(FilesLabelRecordQueryParam query, Pageable pageable) {
        TableDataInfo<FilesTree> info = filesLabelRecordService.queryAll(query, pageable);
        return R.ok(info);
    }


    @GetMapping("/querySelect")
//    @Log("查询标签记录已添加的文件")
//    @ApiOperation("查询标签记录已添加的文件")
    public R<List<FilesLabelRecordVo>> querySelect(FilesLabelRecordQueryParam query) {
        List<FilesLabelRecordVo> dtos = filesLabelRecordService.querySelect(query);
        return R.ok(dtos);
    }

    @GetMapping("/querySelectPage")
//    @Log("查询标签记录已添加的文件分页")
//    @ApiOperation("查询标签记录已添加的文件分页")
    public R<TableDataInfo<FilesLabelRecordVo>> querySelectPage(FilesLabelRecordQueryParam query, Pageable pageable) {
        TableDataInfo<FilesLabelRecordVo> info = filesLabelRecordService.querySelectPage(query, pageable);
        return R.ok(info);
    }

    @PostMapping("/create")
//    @Log("新增标签记录")
//    @ApiOperation("新增标签记录")
    public R<FilesLabelRecordDto> create(@Valid @RequestBody FilesLabelRecordList resources, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建标签记录】参数校验不通过，chooseAPath={}", resources);
            String message = bindingResult.getFieldError().getDefaultMessage();
            log.error(message);
//            throw new BadRequestException(message);
            return R.fail(message);
        }
        List<String> removeLabelId = resources.getRemoveLabelId();
        List<String> labelId = resources.getLabelId();
/*
        if (CollectionUtils.isEmpty(removeLabelId) && CollectionUtils.isEmpty(labelId)) {
            throw new BadRequestException("修改记录标签不可以为空");
            return R.fail("修改记录标签不可以为空");
        }
*/

        LoginUser user = LoginHelper.getLoginUser();
        String labelType = resources.getLabelType();
        FileLabelTypeEnums typeEnums = FileLabelTypeEnums.find(labelType);
        switch (typeEnums){
            case sys:
                Boolean b = enterprisePermService.checkPermission(resources.getFileId(), EnterprisePermTypeEnum.EDITOR, user.getUserId());
                if (!b){
                    throw  new RuntimeException("没有权限添加标签");
                }
                break;
            case team:
                Boolean checked = teamRelevanceRoleService.checkPermission(String.valueOf(resources.getFileId()), resources.getTeamId(),
                        user, TeamParamEnum.LABEL.getParam());
                if (!checked){
                    throw  new RuntimeException("没有权限添加标签，请联系管理员授权权限");
                }
                break;
            case user:
                break;
            default:
                throw new RuntimeException("标签类型");
        }

        boolean delete = false;
        //删除 标签记录
        if (CollectionUtils.isNotEmpty(removeLabelId)) {
            delete = filesLabelRecordService.deleteByLabelFileIds(removeLabelId, resources.getFileType(), resources.getFileId());
        }
        boolean insert = false;
        if (CollectionUtils.isNotEmpty(labelId)) {
            insert = filesLabelRecordService.insert(resources);
        }

        return insert || delete ? R.ok() : R.fail("添加失败");
    }




    @PostMapping("/createList")
//    @Log("多文件新增标签记录")
//    @ApiOperation("多文件新增标签记录")
    public R<FilesLabelRecordDto> createFileLsit(@Valid @RequestBody FilesLabelRecordFileList resources, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【创建标签记录】参数校验不通过，chooseAPath={}", resources);
            String message = bindingResult.getFieldError().getDefaultMessage();
            log.error(message);
//            throw new BadRequestException(message);
            return R.fail(message);
        }

        LoginUser user = LoginHelper.getLoginUser();
        String labelType = resources.getLabelType();
        FileLabelTypeEnums typeEnums = FileLabelTypeEnums.find(labelType);
        List<String> fileIds = resources.getFileIds();
        for (String fileId : fileIds) {
            switch (typeEnums){
                case sys:
                    Boolean b = enterprisePermService.checkPermission(Long.valueOf(fileId), EnterprisePermTypeEnum.EDITOR, user.getUserId());
                    if (!b){
                        throw  new RuntimeException("没有权限添加标签");
                    }
                    break;
//                case team:
//                    Boolean checked = teamRelevanceRoleService.checkPermission(String.valueOf(fileId), resources.getTeamId(),
//                            user, TeamParamEnum.LABEL.getParam());
//                    if (!checked){
//                        throw  new RuntimeException("没有权限添加标签，请联系管理员授权权限");
//                    }
//                    break;
                case user:
                    break;
                default:
                    throw new RuntimeException("标签类型");
            }
        }



        boolean insert = filesLabelRecordService.insertFileList(resources);

        return  insert ? R.ok() : R.fail("添加失败");
    }


    @PostMapping("/delete")
//    @Log("删除标签记录")
//    @ApiOperation("删除标签记录")
    public R delete(@Valid @RequestBody FilesLabelRecordDelete delete) {
        String labelType = delete.getLabelType();
        FileLabelTypeEnums typeEnums = FileLabelTypeEnums.find(labelType);
        switch (typeEnums){
            case sys:
                throw new RuntimeException("缺少企业的关键的编号");
//                break;
//            case team:
//                String teamId = delete.getTeamId();
//                if (StringUtils.isBlank(teamId)) {
//                    throw new RuntimeException("缺少团队关键的编号");
//                }
//                if (!teamMemberService.checkPermission(teamId,
//                        FileUserUtils.getUser(), TeamParamEnum.LABEL.getParam())) {
//                    throw  new RuntimeException("没有权限去删除,联系管理员添加权限");
//                }
//                break;
            case user:
                break;
        }

        LambdaQueryWrapper<FilesLabelRecord> wrapper = new LambdaQueryWrapper<FilesLabelRecord>()
                .in(FilesLabelRecord::getFileId,delete.getIds())
                .eq(FilesLabelRecord::getLabelId,delete.getLabelId())
                .eq(FilesLabelRecord::getFileType,delete.getFileType())
                ;
        boolean remove = filesLabelRecordService.remove(wrapper);
        return  remove ? R.ok() : R.fail("删除失败");
    }


    @GetMapping("/querySys")
//    @Log("查询系统标签的记录")
//    @ApiOperation("查询系统标签的记录")
    public R<List<FilesTree>> querySys(FilesLabelRecordQueryParam query) {
        List<FilesTree> filesTrees = filesLabelRecordService.querySys(query);
        return R.ok(filesTrees);
    }




}
